<template>
  <div class="root" ref="root" v-show="visible">
    <div v-for="menu in menus" :key="menu.name" class="menu-item" @click="menu.handler">
      <div style="width: 20px; height: 20px;" v-html="menu.iconHtml"></div><div style="padding-left: 5px;">{{ menu.name }}</div>
    </div>
  </div>
</template>

<script>
import { createPopper } from '@popperjs/core';
export default {
  props:{
    menus:{
      type:Array,
      default:()=>[]
    }
  },
  data(){
    return {
      visible:false,
      popperInstance:null,
      menuPosition:{x:0,y:0},
      virtualReference:null
    }
  },
  mounted(){
    let _this = this
    this.virtualReference = {
        getBoundingClientRect(){
          return {
            width: 0,
            height: 0,
            top: _this.menuPosition.y,
            bottom: _this.menuPosition.y,
            left: _this.menuPosition.x,
            right: _this.menuPosition.x,
          };
        },
    }
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
    if (this.popperInstance) {
      this.popperInstance.destroy()
      this.popperInstance = null
    }
  },
  methods:{
    show(event){
      this.menuPosition.x=event.clientX
      this.menuPosition.y=event.clientY 
      this.visible = true;
      this.$nextTick(()=>{
          if (this.popperInstance) {
            // 此时 virtualReference 的 getBoundingClientRect 已返回新坐标
            this.popperInstance.update(); // Popper 会重新读取 reference 位置！
          } else {
            this.popperInstance = createPopper(this.virtualReference, this.$refs.root, {
              placement: 'right-start',
              modifiers: [
                {
                  name: 'offset',
                  options: { offset: [0, 0] }
                },
                {
                  name: 'preventOverflow',
                  options: { boundary: document.body }
                }
              ]
            });
          }
      })
    },
    handleClickOutside(event){
      this.visible = false
    }
  }
}
</script>

<style scoped>
.root{
  background: white;
  min-width: 120px;
  min-height: 120px;
  border: 1px solid gray;
  padding: 10px 0px;
  border-radius: var(--theme-border-radius,'2px');
  z-index: 99;
}
.menu-item{
  display:flex;
  align-items: center;
  flex-wrap:nowrap;
  padding: 0 5px;
  cursor: pointer;  
}
.menu-item:hover{
  background-color: var(--theme-primary-color,'#0078d4');
  color: var(--theme-obprimary-color,'white');
}
</style>